package cn.cloudmenu.android.activity;

import java.io.IOException;
import cn.cloudmenu.android.CloudMenuApp;
import java.net.MalformedURLException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import cn.cloudmenu.android.MenuCoverBean;
import cn.cloudmenu.android.R;
import cn.cloudmenu.android.UserProfile;

public class CloudMenu extends Activity implements OnItemSelectedListener, ViewFactory {
	private Gallery gallery;
	private ImageSwitcher imageSwitcher;
	private ImageAdapter imageAdapter;
	private TextView menuTitle;

	//private int[] resIds = new int[] { R.drawable.cover_101, R.drawable.cover_102, R.drawable.cover_103, R.drawable.cover_104, R.drawable.cover_105 };
	private Drawable[] coverSmallLandscape;//Gallery缩略图
	//private Drawable[] coverMiddlePortrait;//封面图
	private MenuCoverBean[] menuCovers;

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		public ImageAdapter(Context context) {
			mContext = context;
			TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
			mGalleryItemBackground = typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);
		}

		// 第1点改进，返回一个很大的值，例如，Integer.MAX_VALUE
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView = new ImageView(mContext);
			// 第2点改进，通过取余来循环取得resIds数组中的图像资源ID
			imageView.setImageDrawable(coverSmallLandscape[position % coverSmallLandscape.length]);
			//imageView.setImageURI(resIds[position % resIds.length]);
			//imageView.setImageResource(resIds[position % resIds.length]);
			//imageView.setScaleType(ImageView.ScaleType.FIT_XY);
			imageView.setScaleType(ScaleType.FIT_CENTER);
			imageView.setLayoutParams(new Gallery.LayoutParams(163, 106));
			imageView.setBackgroundResource(mGalleryItemBackground);
			return imageView;
		}
	}
	private Drawable fetch(String urlString) throws MalformedURLException, IOException {
	    DefaultHttpClient httpClient = new DefaultHttpClient();
	    HttpGet request = new HttpGet(urlString);
	    HttpResponse response = httpClient.execute(request);
	    Drawable drawable = Drawable.createFromStream(response.getEntity().getContent(), "src");
	    return drawable;
	}
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		System.out.println("CloudMenu.onItemSelected() title = " + menuCovers[position % coverSmallLandscape.length].getTitle() );
		// 选中Gallery中某个图像时，在ImageSwitcher组件中放大显示该图像
		imageSwitcher.setImageDrawable(coverSmallLandscape[position % coverSmallLandscape.length]);
		System.out.println("imageSwitcher.setTag() tag.getId() = "+menuCovers[position % coverSmallLandscape.length].getId());
		imageSwitcher.setTag(menuCovers[position % coverSmallLandscape.length]);//store the cover menu data
		menuTitle.setText(menuCovers[position % coverSmallLandscape.length].getName());
		//imageSwitcher.setImageURI(resIds[position % resIds.length]);
		//imageSwitcher.setImageResource(resIds[position % resIds.length]);

	}

	public void onNothingSelected(AdapterView<?> parent) {
	}

	// ImageSwitcher组件需要这个方法来创建一个View对象（一般为ImageView对象）
	// 来显示图像
	public View makeView() {
		ImageView imageView = new ImageView(this);
		imageView.setBackgroundColor(0xFF000000);
		imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
		//imageView.setScaleType(ScaleType.FIT_XY);
		imageView.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return imageView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		//有没有注册信息，如果有，才有可能取出favorite菜单，没有，则进入注册界面
		if(hasUserProfile()){
			System.out.println("CloudMenu.onCreate() hasUserProfile() return true loadMenuList.");
			if(!loadMenuList()){
				//如果有注册信息，但是没有FavoriteMenu，则进入菜单收藏
				Intent intent = new Intent(this, FavoriteMenu.class);
				startActivity(intent);
				return;
			}
		}else{
			System.out.println("CloudMenu.onCreate() hasUserProfile() return false load Profile Activity.");
			Intent intent = new Intent(this, Profile.class);
			this.startActivity(intent);
			return;
		}

		gallery = (Gallery) findViewById(R.id.gallery);
		System.out.println("CloudMenu.onCreate() gallery = "+gallery);
		imageAdapter = new ImageAdapter(this);
		gallery.setAdapter(imageAdapter);
		gallery.setOnItemSelectedListener(this);
		imageSwitcher = (ImageSwitcher) findViewById(R.id.imageswitcher);
		// 设置ImageSwitcher组件的工厂对象
		imageSwitcher.setFactory(this);
		// 设置ImageSwitcher组件显示图像的动画效果
		imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
		imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
		imageSwitcher.setClickable(true);
		imageSwitcher.setOnClickListener(new View.OnClickListener(){
			 public void onClick(View v) {
				 System.out.println("CoverClicked v.Tag() = "+v.getTag());
				 MenuCoverBean menuCover = (MenuCoverBean)v.getTag();
				 System.out.println(menuCover.getName()+" is clicked!");
				 System.out.println(menuCover.getName()+" is clicked! menuCover.getId()="+menuCover.getId());
				 //选择具体菜单后,进入开桌或加入界面
				 Intent intent = new Intent(CloudMenu.this, ChooseTable.class);
				 intent.putExtra("menuId", menuCover.getId());
				 ((CloudMenuApp)CloudMenu.this.getApplication()).setMenu(menuCover);
				 CloudMenu.this.startActivity(intent);
				 /**/
			 }
		});
		
		
		menuTitle = (TextView)findViewById(R.id.menu_title);
		getTitleHeight();
	}
	
	private void getTitleHeight(){
		int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
		Rect frame = new Rect();
		getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); 
		int statusBarHeight = frame.top;   
		//statusBarHeight是上面所求的状态栏的高度   
		int titleBarHeight = contentTop - statusBarHeight;
		System.out.println("getTitleHeight() statusBarHeight = "+statusBarHeight +" titleBarHeight="+titleBarHeight);
	}
	private boolean hasUserProfile(){
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		String href = getResources().getString(R.string.profile_json);
		href = href + tm.getDeviceId();
		System.out.println("CloudMenu.hasUserProfile() href = "+href);
		HttpPost request = new HttpPost(href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据
			String retSrc = EntityUtils.toString(httpResponse.getEntity());

			// 生成 JSON 对象
			System.out.println("CloudMenu.loadMenuList() retSrc = " + retSrc);
			System.out.println("CloudMenu.loadMenuList() retSrc == null " + (retSrc == null));
			JSONObject userProfile = new JSONObject(retSrc);
			System.out.println("CloudMenu.loadMenuList() retSrc = " + retSrc);
			System.out.println("CloudMenu.loadMenuList() userProfile = " + userProfile);
			UserProfile user = new UserProfile();
			user.setUserid(userProfile.getInt("id"));
			user.setNickname(userProfile.getString("nickname"));
			((CloudMenuApp)CloudMenu.this.getApplication()).setUser(user);
			return true;
		} catch (Exception e) {
			//displayMessage(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}

	private boolean loadMenuList() {
		String href = getResources().getString(R.string.favorite_menu_list);
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		href = href + tm.getDeviceId();
		System.out.println("CloudMenu.loadMenuList() href = " + href);
		HttpPost request = new HttpPost(href);
		try {
			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据
			String retSrc = EntityUtils.toString(httpResponse.getEntity());

			// 生成 JSON 对象
			JSONArray favoriteMenu = new JSONArray(retSrc);
			System.out.println("CloudMenu.loadMenuList() favoriteMenu.length = " + favoriteMenu.length());
			if (favoriteMenu.length() < 1) {
				Intent intent = new Intent(this, FavoriteMenu.class);
				this.startActivity(intent);
				return false;
			}else{
				this.coverSmallLandscape = new Drawable[favoriteMenu.length()];
				this.menuCovers = new MenuCoverBean[favoriteMenu.length()];
				for(int i=0; i<favoriteMenu.length(); i++){
					JSONObject menu = favoriteMenu.getJSONObject(i);
					coverSmallLandscape[i] = this.fetch(menu.getString("imagePath")+"/"+menu.getString("coverImage"));
					MenuCoverBean cb = new MenuCoverBean();
					menuCovers[i] = cb;
					cb.setId(menu.getInt("id"));
					cb.setStoreId(menu.getInt("storeId"));
					cb.setTitle(menu.getString("title"));
					cb.setName(menu.getString("name"));
					cb.setImagePath(menu.getString("imagePath"));
					cb.setCoverImage(menu.getString("coverImage"));
					cb.setUpdateTime(new Date(menu.getLong("updateTime")));
				}
				return true;
			}
		} catch (Exception e) {
			displayMessage(e.getMessage());
			e.printStackTrace();
		}
		return false;
	}
	
	@Override 
	   public boolean onCreateOptionsMenu(Menu menu) {
	      super.onCreateOptionsMenu(menu);
	      // Group ID 
	      int groupId = 0; 
	      // The order position of the item 
	      int menuItemOrder = Menu.NONE; 
	      // Create the menu item and keep a reference to it. 
	      
	      MenuItem menuItem = menu.add(groupId, R.integer.menu_item_first, menuItemOrder, this.getString(R.string.menu_item_my_favorite));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_lib_select));

	      menuItem = menu.add(groupId, R.integer.menu_item_second, menuItemOrder, this.getString(R.string.menu_item_together));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_autoreading));

	      menuItem = menu.add(groupId, R.integer.menu_item_third, menuItemOrder, this.getString(R.string.menu_item_my_order));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_settings));

	      menuItem = menu.add(groupId, R.integer.menu_item_fourth, menuItemOrder, this.getString(R.string.menu_item_favorite_set));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_settings));

	      menuItem = menu.add(groupId, R.integer.menu_item_fifth, menuItemOrder, this.getString(R.string.menu_item_my_profile));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_feedback));

	      menuItem = menu.add(groupId, R.integer.menu_item_sixth, menuItemOrder, this.getString(R.string.menu_item_help));
	      menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_profile));
	      return true;
	   }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.integer.menu_item_first) {
			System.out.println("我的菜单");
			Intent intent = new Intent(this, CloudMenu.class);
			startActivity(intent);
			this.finish();
		} else if (item.getItemId() == R.integer.menu_item_second) {
			System.out.println("协同点菜");
			// Intent intent = new Intent(this, MyOrder.class);
			// this.startActivity(intent);
		} else if (item.getItemId() == R.integer.menu_item_third) {
			System.out.println("我的点单");
			Intent intent = new Intent(this, FavoriteMenu.class);
			startActivity(intent);
			this.finish();
			this.finish();

		}  else if (item.getItemId() == R.integer.menu_item_fourth) {
			System.out.println("菜单收藏");
			Intent intent = new Intent(this, FavoriteMenu.class);
			startActivity(intent);
			this.finish();
		} else if (item.getItemId() == R.integer.menu_item_fifth) {
			System.out.println("个人信息");
			Intent intent = new Intent(this, Profile.class);
			this.startActivity(intent);
		} else if (item.getItemId() == R.integer.menu_item_sixth) {
			System.out.println("使用帮助");
			// Intent intent = new Intent(this, GuideShowWord.class);
			// ntent.putExtra("fromShowWordMenu", true);
			// this.startActivity(intent);
		}

		return true;
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(this, message, Toast.LENGTH_LONG);
		t1.show();
	}
}